package com.qijian.tool.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qijian.common.annotation.Log;
import com.qijian.common.core.controller.BaseController;
import com.qijian.common.core.domain.AjaxResult;
import com.qijian.common.core.page.TableDataInfo;
import com.qijian.common.enums.BusinessType;
import com.qijian.common.utils.ObjectUtils;
import com.qijian.common.utils.StringUtils;
import com.qijian.common.utils.mybatis.WhereEntityTool;
import com.qijian.common.utils.poi.ExcelUtil;
import com.qijian.common.utils.uuid.IdUtils;
import com.qijian.tool.domain.App;
import com.qijian.tool.domain.Storage;
import com.qijian.tool.domain.query.AppQuery;
import com.qijian.tool.domain.query.StorageQuery;
import com.qijian.tool.domain.vo.AppVo;
import com.qijian.tool.service.IAppService;
import com.qijian.tool.service.IStorageService;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * App版本Controller
 *
 * @author qijian
 * @date 2022-02-08
 */
@Api(tags = "App版本")
@RestController
@RequiredArgsConstructor
@RequestMapping("/tool/app")
public class AppController extends BaseController {

    private final IAppService appService;
    private final IStorageService storageService;

    /**
     * 查询App版本列表
     */
    @PreAuthorize("@ss.hasPermi('tool:app:list')")
    @GetMapping("/list")
    public TableDataInfo list(AppQuery query, Page<App> page) {
        page.orders().add(OrderItem.desc("create_time"));
        initOrderItem(AppQuery.class, page.orders());
        return getDataTable(appService.page(page, WhereEntityTool.invoke(query)));
    }

    /**
     * 获取最新的app版本
     *
     * @return
     */
    @GetMapping("/latestApp")
    public AjaxResult latestApp() {

        return AjaxResult.success(appService.getLatestApp());
    }


    /**
     * 根据类型获取最新的版本
     */
    @GetMapping("/newest/{type}")
    public AjaxResult newestVersion(@PathVariable String type) {
        if (StringUtils.isBlank(type)) {
            return AjaxResult.success();
        }
        QueryWrapper<App> wrapper = new QueryWrapper<>();
        wrapper.eq("type", type);
        wrapper.eq("update_type", true);
        wrapper.last("limit 1");
        wrapper.orderByDesc("id");
        return AjaxResult.success(appService.getOne(wrapper));
    }

    /**
     * 导出App版本列表
     */
    @PreAuthorize("@ss.hasPermi('tool:app:export')")
    @Log(title = "App版本", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public void export(AppQuery query, HttpServletResponse response) {
        new ExcelUtil<>(App.class).exportExcel(response, appService.list(WhereEntityTool.invoke(query)), "App版本数据");
    }

    /**
     * 获取App版本详细信息
     */
    @PreAuthorize("@ss.hasPermi('tool:app:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(appService.getById(id));
    }

    /**
     * 新增App版本
     */
    @PreAuthorize("@ss.hasPermi('tool:app:add')")
    @Log(title = "App版本", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody AppVo vo) {
        App app = JSONUtil.parse(vo).toBean(App.class);
        app.setId(IdUtils.singletonSnowId());
        // 文件来源更新
        if (ObjectUtil.isNotEmpty(vo.getStorage()) && ObjectUtil.isNotNull(vo.getStorage().getStorageId())) {
            StorageQuery storageQuery = new StorageQuery();
            storageQuery.setStorageId(vo.getStorage().getStorageId());
            Storage storage = new Storage();
            storage.setClassTable(App.class.getSimpleName());
            storage.setClassId(app.getId());
            storageService.update(storage, WhereEntityTool.invoke(storageQuery));
        }
        return toAjax(appService.save(app));
    }

    /**
     * 修改App版本
     */
    @PreAuthorize("@ss.hasPermi('tool:app:edit')")
    @Log(title = "App版本", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody AppVo vo) {
        App app = JSONUtil.parse(vo).toBean(App.class);
        // 文件来源更新
        if (ObjectUtil.isNotEmpty(vo.getStorage()) && ObjectUtils.isNull(app.getId()) && ObjectUtil.isNotNull(vo.getStorage().getStorageId())) {
            StorageQuery storageQuery = new StorageQuery();
            storageQuery.setStorageId(vo.getStorage().getStorageId());
            Storage storage = new Storage();
            storage.setClassTable(App.class.getSimpleName());
            storage.setClassId(app.getId());
            storageService.update(storage, WhereEntityTool.invoke(storageQuery));
        }
        return toAjax(appService.updateById(app));
    }

    /**
     * 删除App版本
     */
    @PreAuthorize("@ss.hasPermi('tool:app:remove')")
    @Log(title = "App版本", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<Long> ids) {
        return toAjax(appService.removeByIds(ids));
    }
}
